#include "logindialog.h"
#include "ui_logindialog.h"
#include "httpmgr.h"
#include "tcpmgr.h"

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    // 设置忘记密码标签的属性
    ui->forget_label->SetState("normal", "normal_hover", "", "selected", "selected_hover", "");

    // 连接http请求登录模块的信号
    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_login_mod_finish,
            this, &LoginDialog::slot_login_mod_finish);
    // 连接登录成功后建立tcp连接的信号和槽函数
    connect(this, &LoginDialog::sig_connect_tcp, TcpMgr::GetInstance().get(), &TcpMgr::slot_tcp_connect);
    // 连接tcp管理者tcp连接建立结束的信号和槽函数
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_con_success, this, &LoginDialog::slot_tcp_con_finish);
    // 连接tcp管理者登录失败的信号和槽函数
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_login_failed, this, &LoginDialog::slot_login_failed);
    // 连接tcp管理者登录成功跳转到聊天界面的信号和槽函数
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_switch_chatdlg, this, &LoginDialog::slot_switch_chatdlg);

    // 注册按钮点击后发送跳转到注册页面信号
    connect(ui->reg_btn, &QPushButton::clicked, this, &LoginDialog::sigSwitchRegister);
    // 重置密码标签点击后发送跳转到重置密码页面信号
    connect(ui->forget_label, &ClickedLabel::clicked, this, &LoginDialog::sigSwitchReset);

    initHttpHandlers();
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::showTip(QString str, bool b_ok)
{
    if (b_ok) {
        ui->err_tip->setProperty("state", "normal");
    } else {
        ui->err_tip->setProperty("state", "err");
    }
    ui->err_tip->setText(str);

    repolish(ui->err_tip);
}

void LoginDialog::initHttpHandlers()
{
    // 注册用户登录回包逻辑
    _handlers.insert(ReqId::ID_LOGIN_USER, [this](QJsonObject jsonObj) {
        int error = jsonObj["error"].toInt();
        if (error != ErrorCodes::SUCCESS) {
            showTip(tr("参数错误"), false);
            return;
        }
        auto user = jsonObj["user"].toString();

        ServerInfo si;
        si.Uid = jsonObj["uid"].toInt();
        si.Host = jsonObj["host"].toString();
        si.Port = jsonObj["port"].toString();
        si.Token = jsonObj["token"].toString();

        _uid = si.Uid;
        _token = si.Token;

        qDebug() << "user is " << user << " uid is " << si.Uid << " host is" << si.Host
                 << " port is " << si.Port << " token is" << si.Token;

        emit sig_connect_tcp(si);
    });
}

void LoginDialog::slot_login_mod_finish(ReqId req_id, QString res, ErrorCodes err)
{
    if (err != ErrorCodes::SUCCESS) {
        showTip("网络请求错误", false);
        return;
    }

    // 将Json字符串转成JsonDocument来反序列化成对象
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());

    if (jsonDoc.isNull()) {
        showTip("json为空", false);
        return;
    }

    if (!jsonDoc.isObject()) {
        showTip("json解析错误", false);
        return;
    }

    // 调用对应的逻辑
    _handlers[req_id](jsonDoc.object());
    return;
}

void LoginDialog::slot_tcp_con_finish(bool bsuccess)
{
    if (bsuccess) {
        showTip("聊天服务器连接成功，正在登录...", true);
        QJsonObject jsonObj;
        jsonObj["uid"] = _uid;
        jsonObj["token"] = _token;
        QJsonDocument doc(jsonObj);
        QByteArray jsonString = doc.toJson(QJsonDocument::Indented);

        emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CHAT_LOGIN, jsonString);

    } else {
        showTip("聊天服务器连接失败！",false);
//        ui->login_btn->setEnabled(true);
    }
}

void LoginDialog::slot_login_failed(int err)
{
    QString result = QString("登录失败，err is %1").arg(err);
    showTip(result, false);

}

void LoginDialog::slot_switch_chatdlg()
{
    qDebug() << "切换到登录界面";
    QString result = QString("切换到登录界面");
    showTip(result, true);
}

void LoginDialog::on_login_btn_clicked()
{
    qDebug() << "login btn clicked";
//    ui->login_btn->setEnabled(false);

    if (!checkUserValid()) {
        return;
    }

    if (!checkPassValid()) {
        return;
    }


    auto email = ui->email_edit->text();
    auto pass = ui->pass_edit->text();

    QJsonObject jsonObj;
    jsonObj["email"] = email;
    jsonObj["passwd"] = pass;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix + "/user_login"), jsonObj, ReqId::ID_LOGIN_USER, Modules::LOGINMOD);
}

bool LoginDialog::checkUserValid()
{
    auto user = ui->email_edit->text();
    if (user.isEmpty()) {
        qDebug() << "User empty";
        return false;
    }
    return true;
}

bool LoginDialog::checkPassValid()
{
    auto pass = ui->pass_edit->text();
    if (pass.size() < 6 || pass.size() > 15) {
       qDebug() << "Pass length invalid";
        return false;
    }
    return true;
}

